<template>
  <view class="detail-query-page">
    <image class="page-bg" src="/static/images/bg.png" mode="aspectFill" />
    <!-- <view class="gradient-bg" :style="{ top: navBarHeight + 'px' }"></view> -->
    <CustomNavbar title="详单查询" />
    
    <view class="page-content" :style="{ paddingTop: navBarHeight + 'px' }">
      <!-- 当前号码 -->
      <view class="phone-info">
        <text class="phone-number">当前号码：{{ phoneNumber }}</text>
      </view>
      
      <!-- 服务类型标签 -->
      <view class="service-type-tabs">
        <view 
          class="tab-item" 
          v-for="(type, index) in serviceTypes" 
          :key="index"
          :class="{ active: currentServiceType === index }"
          @click="switchServiceType(index)"
        >
          {{ type }}
        </view>
      </view>
      
      <!-- 查询周期标签 -->
       <view class="query-period-wrapper">
        <view class="query-period-tabs">
          <view 
            class="period-tab-item" 
            v-for="(period, index) in queryPeriods" 
            :key="index"
            :class="{ active: currentQueryPeriod === index }"
            @click="switchQueryPeriod(index)"
          >
            {{ period }}
          </view>
        </view>
        
        <!-- 月份选择网格 -->
        <view class="month-grid" v-if="currentQueryPeriod === 0">
          <view 
            class="month-item" 
            v-for="(month, index) in monthOptions" 
            :key="index"
            :class="{ active: currentMonthIndex === index }"
            @click="selectMonth(index)"
          >
            {{ month }}
          </view>
        </view>
        
        <!-- 日期选择区域 -->
        <view class="date-selector-wrapper" v-if="currentQueryPeriod === 1">
          <view class="date-selector-item">
            <text class="date-label">开始日期</text>
            <picker 
              mode="date" 
              :value="startDate"
              :start="minDate"
              :end="maxDate"
              @change="onStartDateChange"
            >
              <view class="date-picker-box">
                <text class="date-text" :class="{ placeholder: !startDate }">
                  {{ startDate || '请选择开始日期' }}
                </text>
                <image class="calendar-icon" src="/static/icons/icon-data.png" mode="aspectFit" />
              </view>
            </picker>
          </view>
          <view class="date-selector-item">
            <text class="date-label">结束日期</text>
            <picker 
              mode="date" 
              :value="endDate"
              :start="startDate || minDate"
              :end="maxDate"
              :disabled="!startDate"
              @change="onEndDateChange"
            >
              <view class="date-picker-box" :class="{ disabled: !startDate }">
                <text class="date-text" :class="{ placeholder: !endDate }">
                  {{ endDate || '请选择结束日期' }}
                </text>
                <image class="calendar-icon" src="/static/icons/icon-data.png" mode="aspectFit" />
              </view>
            </picker>
          </view>
        </view>
       </view>
      
      
      <!-- 温馨提示 -->
      <view class="tips-section">
        <view class="section-header">
          <view class="section-line"></view>
          <text class="section-title">温馨提示</text>
        </view>
        <view class="tips-content">
          <text class="tips-text">1、最近60分钟的详单还在路上，可能不在详单查询中噢～。</text>
          <text class="tips-text">2、查询结果仅供参考，实际以营业厅查询结果为准。</text>
        </view>
      </view>
      
      <!-- 查询按钮 -->
      <view class="query-button-wrapper">
        <button class="query-button" @click="handleQuery">查询</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import CustomNavbar from '@/components/CustomNavbar.vue'
import { api } from '@/utils/api'

const navBarHeight = ref(88)
const phoneNumber = ref('189*****0691')
const currentServiceType = ref(0) // 0: 流量, 1: 语音, 2: 短彩信, 3: 增值服务
const currentQueryPeriod = ref(0) // 0: 按月查询, 1: 按日查询
const currentMonthIndex = ref(0) // 当前选中的月份索引
const startDate = ref('') // 开始日期
const endDate = ref('') // 结束日期

// 格式化日期
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 计算最小和最大日期
const minDate = computed(() => {
  const now = new Date()
  const minDateObj = new Date(now.getFullYear(), now.getMonth() - 3, 1)
  return formatDate(minDateObj)
})

const maxDate = computed(() => {
  const now = new Date()
  return formatDate(now)
})

const serviceTypes = ref(['流量', '语音', '短彩信', '增值服务'])
const queryPeriods = ref(['按月查询', '按日查询'])

// 生成月份选项
const monthOptions = computed(() => {
  const months = ['本月']
  const now = new Date()
  const currentYear = now.getFullYear()
  const currentMonth = now.getMonth() + 1
  
  // 生成最近5个月（不包括本月）
  for (let i = 1; i <= 5; i++) {
    const date = new Date(currentYear, currentMonth - i, 1)
    const year = date.getFullYear()
    const month = date.getMonth() 
    months.push(`${year}年 ${month}月`)
  }
  
  return months
})

onMounted(() => {
  const windowInfo = uni.getWindowInfo()
  const statusBarHeight = windowInfo.statusBarHeight || 0
  navBarHeight.value = statusBarHeight + 44

  // 初始化查询详单 '流量':113 '语音':111 '短彩信':112 '增值服务':115
  // getDetailList(currentServiceType.value, monthOptions.value[currentMonthIndex.value], startDate.value, endDate.value)
  // getDetailList('113', '202509', startDate.value, endDate.value)

})

// 查询详单
const getDetailList = (queryType, queryMonth, queryBeginTime, queryEndTime) => {
  api.getDetailList({
    queryType: queryType,
    queryMonth:queryMonth?queryMonth:'',
    // queryBeginTime:queryBeginTime?queryBeginTime:'',
    // queryEndTime:queryEndTime?queryEndTime:'' 
  }).then(res => {
    console.log('查询详单响应:', JSON.stringify(res))
    if (res.code === 200) {
      // 处理查询成功逻辑
      uni.showToast({
        title: '查询成功',
        icon: 'success',
        duration: 2000
      })
    } else {
      uni.showToast({
        title: res.msg || '查询失败',
        icon: 'none',
        duration: 2000
      })
    }
  }).catch(err => {
    console.error('查询失败:', err)
 
  })
}

const switchServiceType = (index) => {
  currentServiceType.value = index
  console.log('切换服务类型:', serviceTypes.value[index])
}

const switchQueryPeriod = (index) => {
  currentQueryPeriod.value = index
  console.log('切换查询周期:', queryPeriods.value[index])
}

const selectMonth = (index) => {
  currentMonthIndex.value = index
  console.log('选择月份:', monthOptions.value[index])
}

// 开始日期改变
const onStartDateChange = (e) => {
  startDate.value = e.detail.value
  // 如果结束日期早于开始日期，清空结束日期
  if (endDate.value && endDate.value < startDate.value) {
    endDate.value = ''
  }
  console.log('选择开始日期:', startDate.value)
}

// 结束日期改变
const onEndDateChange = (e) => {
  endDate.value = e.detail.value
  console.log('选择结束日期:', endDate.value)
}

const handleQuery = () => {
  const serviceType = serviceTypes.value[currentServiceType.value]
  const queryPeriod = queryPeriods.value[currentQueryPeriod.value]
  
  let queryParams = {
    serviceType,
    queryPeriod,
    phoneNumber: phoneNumber.value
  }
  
  if (currentQueryPeriod.value === 0) {
    // 按月查询
    const selectedMonth = monthOptions.value[currentMonthIndex.value]
    queryParams.selectedMonth = selectedMonth
  } else {
    // 按日查询
    if (!startDate.value || !endDate.value) {
      uni.showToast({
        title: '请选择完整的日期范围',
        icon: 'none',
        duration: 2000
      })
      return
    }
    queryParams.startDate = startDate.value
    queryParams.endDate = endDate.value
  }
  
  console.log('查询参数:', queryParams)
  
  // 跳转到身份验证页面，传递查询参数
  const paramsString = encodeURIComponent(JSON.stringify(queryParams))
  uni.navigateTo({
    url: `/pages/auth/auth?queryParams=${paramsString}`,
    success: () => {
      console.log('跳转到身份验证页面成功')
    },
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '跳转失败',
        icon: 'none',
        duration: 2000
      })
    }
  })
}
</script>

<style scoped>
.detail-query-page {
   
  position: relative;
  z-index: 1;
  padding-bottom: 200rpx;
}

.page-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: -1;
  pointer-events: none;
  object-fit: cover;
}

.gradient-bg {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  pointer-events: none;
  background: rgba(255, 255, 255, 0.4);
}

.page-content {
  position: relative;
  z-index: 2;
  padding: 40rpx 32rpx;
  padding-bottom: 200rpx;
}

/* 当前号码 */
.phone-info {
  margin-top: 40rpx;
  margin-bottom: 40rpx;
}

.phone-number {
  color: rgba(255, 255, 255, 1);
  font-family: HarmonyOS Sans SC;
  font-size: 32rpx;
  font-weight: 700;
  line-height: 38rpx;
}

/* 服务类型标签 */
.service-type-tabs {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32rpx;
  gap: 16rpx;
}

.tab-item {
  flex: 1;
  padding: 16rpx 0;
  color: rgba(255, 255, 255, 0.8);
  font-family: HarmonyOS Sans SC;
  font-size: 32rpx;
  font-weight: 400;
  line-height: 38rpx;
  text-align: center;
  border-radius: 8rpx;
  transition: all 0.3s ease;
}

.tab-item.active {
  border-radius: 20rpx;
  backdrop-filter: blur(8px);
  background: rgba(255, 255, 255, 1);
  color: rgba(78, 138, 254, 1);
  font-weight: 500;
}

/* 查询周期标签 */
.query-period-wrapper{
  border-radius: 16rpx;
background: rgba(255, 255, 255, 1);
}
.query-period-tabs {
  display: flex;
  gap: 24rpx;
  justify-content: space-evenly;
}

.period-tab-item {
  padding: 24rpx 32rpx 8rpx 32rpx;
  color: rgba(102, 102, 102, 1);
font-family: HarmonyOS Sans SC;
font-size: 32rpx;
font-weight: 400;
line-height: 38rpx;
  text-align: center;
  transition: all 0.3s ease;
}

.period-tab-item.active {
  backdrop-filter: blur(8px);
  background: rgba(255, 255, 255, 1);
  border-radius: 16rpx 16rpx 0 0;
  color: rgba(78, 138, 254, 1);
  font-weight: 500;
  border-bottom: 4rpx solid rgba(78, 138, 254, 1);
}

/* 月份选择网格 */
.month-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24rpx;
  margin-bottom: 32rpx;
  padding: 24rpx;
}

.month-item {
  padding: 24rpx 48rpx;
    box-sizing: border-box;
    border-radius: 16rpx;
    box-shadow: 0px 2rpx 8rpx 0px rgba(59, 91, 137, 0.04);
    background: rgba(246, 246, 246, 1);
    text-align: center;
    color: rgba(51, 51, 51, 1);
    font-family: HarmonyOS Sans SC;
    font-size: 28rpx;
    font-weight: 400;
    line-height: 32rpx;
    transition: all 0.3s ease;
    backdrop-filter: blur(10rpx);
    -webkit-backdrop-filter: blur(10rpx);
    display: flex;
    align-items: center;
    justify-content: center;
}

.month-item.active {
  background: rgba(78, 138, 254, 1);
  color: rgba(255, 255, 255, 1);
  font-weight: 500;
  box-shadow: 0px 4rpx 12rpx rgba(78, 138, 254, 0.3);
}

/* 日期选择区域 */
.date-selector-wrapper {
  padding: 24rpx;
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.date-selector-item {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.date-label {
  color: rgba(51, 51, 51, 1);
  font-family: HarmonyOS Sans SC;
  font-size: 28rpx;
  font-weight: 400;
  line-height: 32rpx;
}

.date-picker-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 32rpx;
  background: rgba(246, 246, 246, 1);
  border-radius: 16rpx;
  box-shadow: 0px 2rpx 8rpx 0px rgba(59, 91, 137, 0.04);
  transition: all 0.3s ease;
}

.date-picker-box:active {
  opacity: 0.8;
}

.date-text {
  flex: 1;
  color: rgba(51, 51, 51, 1);
  font-family: HarmonyOS Sans SC;
  font-size: 28rpx;
  font-weight: 400;
  line-height: 32rpx;
}

.date-text.placeholder {
  color: rgba(153, 153, 153, 1);
}

.date-picker-box.disabled {
  opacity: 0.6;
}

.calendar-icon {
  width: 32rpx;
  height: 32rpx;
  flex-shrink: 0;
}

/* 温馨提示 */
.tips-section {
  margin-bottom: 40rpx;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}

.section-line {
  width: 8rpx;
  height: 40rpx;
  background: rgba(78, 138, 254, 1);
  border-radius: 4rpx;
  margin-right: 16rpx;
}

.section-title {
  color: rgba(51, 51, 51, 1);
  font-family: HarmonyOS Sans SC;
  font-size: 32rpx;
  font-weight: 700;
  line-height: 38rpx;
}

.tips-content {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.tips-text {
  color: rgba(153, 153, 153, 1);
  font-family: HarmonyOS Sans SC;
  font-size: 24rpx;
  font-weight: 400;
  line-height: 28rpx;
}

/* 查询按钮 */
.query-button-wrapper {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 32rpx;
  /* padding-bottom: calc(32rpx + env(safe-area-inset-bottom)); */
  /* background: rgba(255, 255, 255, 0.95); */
  /* backdrop-filter: blur(20rpx);
  -webkit-backdrop-filter: blur(20rpx); */
  z-index: 100;
  /* box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.05); */
}

.query-button {
  width: 100%;
  height: 88rpx;
  background: rgba(78, 138, 254, 1);
  color: rgba(255, 255, 255, 1);
  border-radius: 44rpx;
  font-family: HarmonyOS Sans SC;
  font-size: 32rpx;
  font-weight: 500;
  line-height: 88rpx;
  text-align: center;
  border: none;
  box-shadow: 0px 4rpx 12rpx rgba(78, 138, 254, 0.3);
}

.query-button::after {
  border: none;
}

.query-button:active {
  opacity: 0.8;
}
</style>
